package targetToOffer.firstDay;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Godc
 * @description 逆序输出链表
 */
public class TailToHeadPrint {
    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        head.next = node1;
        node1.next = node2;
        int[] ints = solution.reversePrint2(head);


    }
}
class Solution {
    /**
     * 第一种方法，辅助栈
     * @param head
     * @return
     */
    public int[] reversePrint(ListNode head) {
        Deque<Integer> stack = new LinkedList<Integer>();
        while(head!=null) {
            stack.push(head.val);
            head = head.next;
        }
        int[] ints = new int[stack.size()];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = stack.pop();
        }
        return ints;
    }

    /**
     * 第二种方法，使用递归法
     */
    int[] res;
    int i;
    int j;
    public int[] reversePrint2(ListNode head){
        solve(head);
        return res;
    }
    public void solve(ListNode head){
        if(head == null){
            res = new int[i];
            return;
        }
        i++;
        solve(head.next);
        res[j] = head.val;
        j++;
    }
}
class ListNode {

    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
